from django.utils import six
from django.utils.crypto import salted_hmac
from django.utils.image import Image
import math
import time


def image_center_resize(image, size, resample=Image.NEAREST):
    if not isinstance(image, Image.Image):
        image = Image.open(image)

    x, y = image.size
    if x < size[0] or y < size[1]:
        if x < size[0]:
            y = max(y * size[0] / x, 1)
            x = size[0]
        if y < size[1]:
            x = max(x * size[1] / y, 1)
            y = size[1]
    else:
        ratio = max((size[0] + 0.0) / x, (size[1] + 0.0) / y)
        x = int(math.ceil(x * ratio))
        y = int(math.ceil(y * ratio))

    im = image.resize((x, y), resample)
    x1 = (x - size[0]) / 2
    y1 = (y - size[1]) / 2
    x2 = x1 + size[0]
    y2 = y1 + size[1]
    return im.crop((x1, y1, x2, y2))


def generate_token_by_user(user, key_salt=''):
    value = (six.text_type(user.pk) + six.text_type(time.time()))
    return salted_hmac(key_salt, value).hexdigest()
